package se_dsp_report

import (
	"fmt"
	"sync"
	"time"
	"wx-api/dsp-api/config"
)

var AutoDataCache = new(sync.Map)

func GetAutoDataCache(id string) AutoData {
	tmp, ok := AutoDataCache.Load(id)
	if ok {
		return tmp.(AutoData)
	}
	return AutoData{}
}

type AutoData struct {
	Req   int64
	Fill  int64
	Pv    int64
	Click int64
	Price float64
}

func AutoDspReport() {
	sdate := time.Now().Format("2006-01-02")
	edate := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
	sql := "select date,media_id,app_id,slot_id,adv_id,plan_id,sum(req) as req,sum(fill) as fill, " +
		"sum(pv) as pv, sum(ipv) as ipv, sum(click) as click, sum(iclick) as iclick, " +
		"sum(deeplink) as deeplink,sum(ideeplink) as ideeplink,sum(price) as price " +
		"from " + config.CkTableReport
	where := " where date <='" + sdate + "' and date >= '" + edate + "'"
	order := " order by date desc"
	group := " group by date,media_id,app_id,slot_id,adv_id,plan_id"

	sql = sql + where + group + order
	ret := []DspCkReport{}
	err := config.CKDB.Select(&ret, sql)
	if err != nil {
		fmt.Println("AutoDspReport select error:" + err.Error())
		return
	}
	//今日
	DoAutoDspReport(sdate, "t", ret)
	//昨日
	DoAutoDspReport(edate, "y", ret)
}
func DoAutoDspReport(dd string, ty string, ret []DspCkReport) {
	//账户纬度
	adv_arr := make(map[string]AutoData)
	plan_arr := make(map[string]AutoData)
	for _, report := range ret {
		ddd := report.Date[0:10]
		if dd == ddd {
			tmp, ok := adv_arr[report.AdvId]
			if !ok {
				tmp = AutoData{
					Req:   report.Req,
					Fill:  report.Fill,
					Pv:    report.Pv,
					Click: report.Click,
					Price: report.Price,
				}
			} else {
				tmp.Req += report.Req
				tmp.Fill += report.Fill
				tmp.Pv += report.Pv
				tmp.Click += report.Click
				tmp.Price += report.Price
			}
			adv_arr[report.AdvId] = tmp
			//计划
			tmpp, ok := plan_arr[report.PlanId]
			if !ok {
				tmpp = AutoData{
					Req:   report.Req,
					Fill:  report.Fill,
					Pv:    report.Pv,
					Click: report.Click,
					Price: report.Price,
				}
			} else {
				tmpp.Req += report.Req
				tmpp.Fill += report.Fill
				tmpp.Pv += report.Pv
				tmpp.Click += report.Click
				tmpp.Price += report.Price
			}
			plan_arr[report.PlanId] = tmpp
		}
	}
	for sa, adv := range adv_arr {
		AutoDataCache.Store("adv-"+ty+"-"+sa, adv)
	}
	for sp, plan := range plan_arr {
		AutoDataCache.Store("plan-"+ty+"-"+sp, plan)
	}
}
